package com.example.demopublish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demopublish.dto.UserDto;
import com.example.demopublish.entity.JwUser;
import com.example.demopublish.mapper.JwUserMapper;
import com.example.demopublish.service.JwUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangwei
 * @since 2025-01-07
 */
@Service
public class JwUserServiceImpl extends ServiceImpl<JwUserMapper, JwUser> implements JwUserService {

    @Override
    public int saveOne(UserDto dto) {
        JwUser jwUser = new JwUser();
        BeanUtils.copyProperties(dto, jwUser);
        jwUser.setCreateTime(new Date());
        jwUser.setUpdateTime(new Date());
        return this.getBaseMapper().insert(jwUser);
    }

    @Override
    public Page<JwUser> selectPageInfo(UserDto dto) {
        Long dtoPage = dto.getPage();
        Long size = dto.getSize();
        if (ObjectUtils.isEmpty(dtoPage) || ObjectUtils.isEmpty(size)) {
            throw new RuntimeException("缺少必填参数");
        }

        LambdaQueryWrapper<JwUser> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getUsername())) {
            queryWrapper.like(JwUser::getName, dto.getUsername());
        }
        queryWrapper.orderByDesc(JwUser::getCreateTime);

        Page page = new Page(dtoPage, size);

        Page resultPage = this.getBaseMapper().selectPage(page, queryWrapper);
        return resultPage;
    }

    @Override
    public List<JwUser> getOneByWrapper(UserDto dto) {
        LambdaQueryWrapper<JwUser> queryWrapper = new LambdaQueryWrapper<>();
        addCondition(queryWrapper, dto);
        return this.getBaseMapper().selectList(queryWrapper);
    }

    private void addCondition(LambdaQueryWrapper<JwUser> queryWrapper, UserDto dto) {
        if (StringUtils.isNotBlank(dto.getUsername())) {
            queryWrapper.like(JwUser::getName, dto.getUsername());
        }

        if (ObjectUtils.isNotEmpty(dto.getPassword())) {
            queryWrapper.eq(JwUser::getPassword, dto.getPassword());
        }

    }
}
